package com.greyshark.lib.bluetooth.receive

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.greyshark.lib.bluetooth.ControlCenterClient
import com.greyshark.lib.bluetooth.utils.LogUtils

class BluetoothReceiver : BroadcastReceiver() {

  private val tag: String = BluetoothReceiver::class.java.simpleName

  override fun onReceive(context: Context?, intent: Intent) {
    when (intent.action) {
      BluetoothAdapter.ACTION_STATE_CHANGED -> {
        val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
        when (state) {
          BluetoothAdapter.STATE_TURNING_ON -> {
            LogUtils.i(tag, "blueStateChange STATE_TURNING_ON")
          }

          BluetoothAdapter.STATE_ON -> {
            LogUtils.i(tag, "blueStateChange STATE_ON")
            //系统休眠关闭蓝牙不会走STATE_OFF,故需重启蓝牙服务. 分别disconnect,release,init
            ControlCenterClient.instance.disconnect()
            ControlCenterClient.instance.release()
            ControlCenterClient.instance.context?.let {
              ControlCenterClient.instance.initialize(
                context = it,
                initSuccess = {
                  ControlCenterClient.instance.connect(
                    name = ControlCenterClient.instance.deviceName,
                    address = ControlCenterClient.instance.deviceAddress
                  )
                },
                initFailure = {},
              )
            }
          }

          BluetoothAdapter.STATE_TURNING_OFF -> {
            LogUtils.i(tag, "blueStateChange STATE_TURNING_OFF")
            ControlCenterClient.instance.release()
          }

          BluetoothAdapter.STATE_OFF -> {
            LogUtils.i(tag, "blueStateChange STATE_OFF")
            ControlCenterClient.instance.release()
          }
        }
      }
    }
  }
}